package cn.ylz.ylmall.account.security;

import cn.ylz.ylmall.account.dao.persist.repository.IUserRepository;
import cn.ylz.ylmall.account.pojo.vo.UserLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private IUserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserLoginInfoVO infoVO = userRepository.selectByUsername(s);
        log.debug("infovo,{}",infoVO);

        if (infoVO == null){
            return null;
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> permissions = infoVO.getPermissions();
        for (String permission:permissions){
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }

        CustomUserDetails userDetails = new CustomUserDetails(infoVO.getId(),infoVO.getUsername(),
                infoVO.getPassword(), infoVO.getAvatar(),infoVO.getEmail(),infoVO.getPhone(),infoVO.getEnable()==1,authorities);
        return userDetails;
    }
}
